package com.v0710.docommon.exception;

import cn.hutool.core.lang.Console;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.v0710.docommon.dto.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestControllerAdvice
public class SysExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(SysExceptionHandler.class);

    @Autowired(required = false)
    public HttpServletResponse httpServletResponse;

    @ExceptionHandler(SysException.class)
    public R<?> handleSysException(SysException e){
        log.error("\n"+ Console.where()+e.getMessage());
        log.error("=================================");
        log.error(String.valueOf(e));
        if (e.getMessage()!=null && e.getMessage().contains("token"))
            return R.error(401,e.getMessage());
        return R.error(e.getCode(),"RuntimeException#异常：" + e.getMsg());
    }

    @ExceptionHandler(Throwable.class)
    public R<?> handleException(Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> paramMap = ServletUtil.getParamMap(request);
        System.out.println();
        log.error("URL={}", request.getRequestURL());
        log.error("param={}", JSONUtil.toJsonStr(paramMap));
        log.error("ContentType={}", request.getContentType());
        log.error("\n{}[#Throwable#异常]{}"+Console.where(),e.getMessage());
        log.error("=================================");
        log.error("Throwable#异常：{}",String.valueOf(e));
//        log.error("#Throwable#异常", e);
        return R.error(501,"Throwable#异常："+e.getMessage());
    }


}
